<template>
  <div class="body">
    <div class="table_filtrate">
      <div v-if="jsAuthJudgment('manage')" class="tf_item">
        <div class="tag">商务</div>

        <el-select v-model="tableParams.business_uid" class="input" placeholder="请选择" size="mini">
          <el-option label="全部" :value="0" />
          <el-option v-for="item in tableFiltrateData.business_list" :key="item.id" :label="item.nickname"
            :value="item.id">
            <span style="float: left">{{ item.nickname }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{
              item.group_name
            }}</span>
          </el-option>
        </el-select>
      </div>

      <div class="tf_item">
        <div class="tag">助贷类型</div>

        <el-select v-model="tableParams.loantype" class="input" size="mini" placeholder="请选择">
          <el-option label="全部" value="all" />
          <el-option label="全国" value="nationwide" />
          <el-option label="区域" value="region" />
          <el-option label="同业" value="peer" />
        </el-select>
      </div>

      <div class="tf_item">
        <div class="tag">搜索</div>

        <el-input v-model="tableParams.fuzzy_search" size="mini" class="input_fuzzy_search input" placeholder="ID|名字"
          clearable />
      </div>

      <div class="tf_item">
        <div class="tag">状态</div>

        <el-select v-model="tableParams.status" class="input" placeholder="请选择" size="mini">
          <el-option label="全部" value="all" />
          <el-option label="正常" value="normal" />
          <el-option label="废弃" value="stop" />
          <el-option label="待审核" value="await" />
        </el-select>
      </div>

      <div class="tf_item">
        <el-button type="primary" plain size="mini" @click="loadTableData">搜索</el-button>
      </div>
    </div>

    <div class="table_operate">
      <div class="tool-temp">
        <el-button class="btn_add" type="primary" size="mini" @click="handleToGoCreate()">添加</el-button>
      </div>

      <div class="tool-self">
        <el-button class="btn_export" type="info" size="mini" @click="exportExcelFun()">导出<i
            class="el-icon-download el-icon--right" /></el-button>
      </div>
    </div>

    <div class="table-card">
      <el-table id="table_id" v-loading="loading.table" class="table" :data="tableData.data" size="mini" border
        style="width: 100%" show-summary :summary-method="$_App_getSummaries">
        <el-table-column sortable prop="id" label="ID" width="80" />
        <el-table-column sortable prop="name" label="名字" width="140" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span slot="reference" class="ellipsis custom-link" style="font-size: 12px">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable prop="phone" label="手机号" width="120">
          <template slot-scope="scope">
            <el-link v-if="scope.row.phone_show == false" type="primary"
              @click="scope.row.phone_show = true">立即查看</el-link>
            <div v-else> {{ scope.row.phone }}</div>
          </template>
        </el-table-column>
        <el-table-column sortable prop="loantype_text" label="贷款类型" />
        <el-table-column sortable label="所属商务" width="140">
          <template slot-scope="scope">
            <div>{{ scope.row.business.nickname }}</div>
          </template>
        </el-table-column>
        <el-table-column sortable prop="balance" label="余额" />
        <el-table-column sortable prop="today_cost" label="当天消耗" />
        <el-table-column sortable prop="total_cost" label="累计消耗" />
        <el-table-column sortable label="推送状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.push_status_switch" active-color="#13ce66" inactive-color="#ff4949" @change="
              handleTableUpdateData($event, scope.row.id, 'push_status')
              " />
          </template>
        </el-table-column>
        <el-table-column sortable label="进件状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.entry_status_switch" disabled active-color="#13ce66" inactive-color="#ff4949"
              @change="
                handleTableUpdateData($event, scope.row.id, 'entry_status')
                " />
          </template>
        </el-table-column>
        <el-table-column sortable prop="product_count" label="产品数量">
          <template slot-scope="scope">
            <el-link target="_blank" @click="handleToGoProduct(scope.row)">{{
              scope.row.product_count
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column sortable label="状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == 'normal'" type="success" plain>正常</el-tag>
            <el-tag v-else-if="scope.row.status == 'failure'" type="info" plain>驳回</el-tag>
            <el-tag v-else-if="scope.row.status == 'await'" type="warning" plain>待审核</el-tag>
            <el-tag v-else-if="scope.row.status == 'stop'" type="danger" plain>已废弃</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="175">
          <template slot-scope="scope">
            <el-link v-show="scope.row.status == 'normal'" class="handle" type="primary" @click="
              handleToGoTransaction(scope.$index, scope.row, 'recharge')
              ">充值</el-link>

            <el-link v-show="scope.row.status == 'normal'" class="handle" type="primary"
              @click="handleToGoTransaction(scope.$index, scope.row, 'expense')">退款</el-link>

            <el-link v-show="scope.row.status == 'stop'" class="handle" type="warning"
              @click="handleTableRegain(scope.$index, scope.row)">恢复</el-link>

            <el-link v-show="scope.row.status == 'normal'" class="handle" type="primary"
              @click="handleTableEdit(scope.$index, scope.row)">编辑</el-link>
            <el-link v-show="scope.row.status == 'normal'" class="handle" type="danger"
              @click="handleTableDelete(scope.$index, scope.row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination v-if="!loading.table" class="table-pagination-card" :current-page="tableParams.page"
        :page-sizes="$pageSize" :page-size="tableParams.size"
        layout="total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="handleTableSizeChange"
        @current-change="handleTableCurrentChange" />
    </div>
  </div>
</template>

<script>
import {
  apiAgentList,
  apiGroupList,
  apiAgentCreate,
  apiAgentUpdate,
  apiOrganizationListpage,
  apiOrganizationDel,
  apiOrganizationUpdateSingle
} from '@/api/apiCommon'
import { authJudgment, App_getSummaries } from '@/utils/appUtil'
import { exportExcel } from '@/utils/htmlToExcelUtils'
export default {
  name: 'Index',
  data() {
    return {
      tableParams: {
        page: 1,
        size: 30,
        status: 'normal',
        fuzzy_search: '',
        business_uid: 0,
        loantype: 'all'
      },
      tableData: {
        current_page: 1,
        data: [],
        last_page: 1,
        per_page: '30',
        total: 0
      },
      loading: {
        dialog_create: false,
        table: false
      },
      tableFiltrateData: {
        business_list: []
      },
      currentPage4: 1,
      dialogConfig: {
        title: '添加人员'
      },
      dialogFormVisible: true,
      fromViewCofing: {
        input_width: '120px',
        label_width: '120px'
      },
      init_form: {},
      form: {
        id: 0,
        logo_img: '',
        name: '',
        phone: '',
        username: '',
        password: '',
        confirm_password: '',
        loantype: 'nationwide',
        loan_min: '100',
        loan_max: '10000',
        business_license_img: '',
        corporate_card_img: '',
        office_video: '',
        cooperation_agreement_img: '',
        commitment_letter_img: '',
        push_status: '1',
        entry_status: '0',
        sms_notification_status: '1',
        balance_display_status: '0',
        consumption_display_status: '1',
        loan_cycle: '36',
        apr: '16'
      }
    }
  },
  created() {
    this.init_form = this.form
    if (this.jsAuthJudgment('manage')) {
      this.req_agent()
    }
    this.loadTableData()
  },
  methods: {
    // 获取商务人员
    req_agent() {
      const _this = this
      apiAgentList({
        page: 1,
        size: 99,
        status: 'normal',
        group_id: '2,3,5'
      })
        .then((response) => {
          const result = response.data.datalist.data
          _this.tableFiltrateData.business_list = result
        })
        .catch(function (result) {
          _this.$message.error(result.msg)
        })
    },
    // 列表请求
    loadTableData(is_initpage = false) {
      const _this = this
      this.loading_start('table')

      if (is_initpage) {
        this.tableParams.page = 1
      }

      var tableParams = { ...this.tableParams }

      if (tableParams.fuzzy_search == '') {
        delete tableParams.fuzzy_search
      }
      if (tableParams.business_uid == 0) {
        delete tableParams.business_uid
      }
      if (tableParams.loantype == 'all') {
        delete tableParams.loantype
      }
      apiOrganizationListpage(tableParams)
        .then((response) => {
          const result = response
          var tableData = result.data.datalist
          var data = tableData.data

          for (var i = 0; i < data.length; i++) {
            data[i]['push_status_switch'] = false
            data[i]['entry_status_switch'] = false
            if (data[i]['push_status'] == 1) {
              data[i]['push_status_switch'] = true
            }
            if (data[i]['entry_status'] == 1) {
              data[i]['entry_status_switch'] = true
            }

            if (data[i]['entry_status'] == 1) {
              data[i]['entry_status_switch'] = true
            }

            if (data[i]['loantype'] == 'nationwide') {
              data[i]['loantype_text'] = '全国'
            } else if (data[i]['loantype'] == 'region') {
              data[i]['loantype_text'] = '区域'
            } else if (data[i]['loantype'] == 'peer') {
              data[i]['loantype_text'] = '同业'
            }
            data[i]['phone_show'] = false
            if (!data[i]['phone']) {
              data[i]['phone'] = '无'
            }
          }
          tableData.data = data
          _this.tableData = tableData
          this.loading_end('table')
        })
        .catch(function (result) {
          _this.tableData.data = null
          this.loading.status = false
        })
    },
    // 初始化表单数据
    from_init() {
      this.form = {
        id: 0,
        name: '',
        logo_img: '',
        password_confirmation: '',
        mobile: '',
        nickname: '',
        group_id: '',
        status: 'normal'
      }
    },
    // 跳转添加页面
    handleToGoCreate() {
      this.$router.push({ path: '/organization/create', query: { id: 0 } })
    },
    // 跳转入账页面
    handleToGoTransaction(index, row, transaction_type) {
      this.$router.push({
        path: '/organization/transaction',
        query: { id: row.id, transaction_type: transaction_type }
      })
    },
    // 跳转产品页面
    handleToGoProduct(row) {
      var business_uid = row.business_uid
      var id = row.id
      console.log(row, 'rowrowrowrowrow')
      this.$router.push({
        path: '/product/index',
        query: {
          business_uid: business_uid,
          o_id: id
        }
      })
    },
    // 表格操作
    handleTableEdit(index, row) {
      this.$router.push({
        path: '/organization/update',
        query: { id: row.id }
      })
    },
    // 表格 手机号显示
    handleTablePhoneShow(index, row) {
      _this.tableData[index]['phone_show'] = true
    },
    // 表格恢复
    handleTableRegain(index, row) {
      var _this = this
      var params = {
        id: row.id,
        status: 'normal'
      }
      this.$confirm('是否恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          _this.loading_start('table')
          apiOrganizationUpdateSingle(params)
            .then((response) => {
              _this.loadTableData()
              _this.$message({
                message: '更新成功',
                type: 'success'
              })
            })
            .catch(function (result) {
              _this.loading_end('table')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 更新状态
    handleTableUpdateData($event, id, key) {
      const _this = this
      var status = 0
      if ($event) {
        status = 1
      }
      var param = {
        id: id
      }
      param[key] = status

      this.$confirm('是否更改状态', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiOrganizationUpdateSingle(param).then((response) => {
            _this.$message({
              message: '更新成功',
              type: 'success'
            })
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 表格删除
    handleTableDelete(index, row) {
      console.log(index, row)
      const _this = this

      this.$confirm('是否删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          _this.loading_start('table')
          apiOrganizationDel({ id: row.id })
            .then((response) => {
              _this.$message({
                message: '删除成功',
                type: 'success'
              })
              _this.loadTableData()
            })
            .catch(function (result) {
              _this.loading_end('table')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 导出表格
    exportExcelFun() {
      const _this = this
      var data = _this.tableData.data
      for (var t = 0; t < data.length; t++) {
        data[t]['phone_show'] = true
      }
      _this.tableData.data = data

      setTimeout(function () {
        exportExcel('机构')
      }, 1000)

      setTimeout(function () {
        for (var t = 0; t < data.length; t++) {
          data[t]['phone_show'] = false
        }
        _this.tableData.data = data
      }, 3000)
    },
    // 打开添加/修改输入框
    handleDialogVisible(status, is_init_from = true) {
      if (is_init_from) {
        this.from_init()
      }
      this.dialogFormVisible = status
    },
    /** 表单提交 */
    fromSubmit() {
      const _this = this
      var form = this.form
      console.log(form)
      if (form.password.length > 0 || form.password_confirmation.length > 0) {
        if (form.password != form.password_confirmation) {
          this.$message.error('二次输入密码不一致，请重新输入')
          return false
        }
      }
      if (form.id == 0) {
        apiAgentCreate(_this.form).then((response) => {
          console.log(response, 'response')
          this.handleDialogVisible(false)
          _this.$message({
            message: response.msg,
            type: 'success'
          })
          _this.loadTableData()
          _this.from_init()
        })
      } else {
        apiAgentUpdate(_this.form).then((response) => {
          console.log(response, 'response')
          _this.dialogFormVisible = false
          _this.$message({
            message: response.msg,
            type: 'success'
          })
          _this.loadTableData()
        })
      }
    },
    // 数量改变
    handleTableSizeChange(val) {
      this.tableParams.size = val
      this.loadTableData(false)
    },
    // 页数改变
    handleTableCurrentChange(val) {
      this.tableParams.page = val
      this.loadTableData(false)
      // console.log(`当前页: ${val}`);
    },
    getSummaries(param) {
      return App_getSummaries(param)
    },
    // 权限判断
    jsAuthJudgment(agree_group) {
      return authJudgment(agree_group)
    },
    // 加载开始...
    loading_start(keys) {
      if (Array.isArray(keys)) {
        keys.forEach((key) => {
          this.loading[key] = true
          setTimeout(() => {
            this.loading[key] = false
          }, 5000)
        })
      } else {
        this.loading[keys] = true
        setTimeout(() => {
          this.loading[keys] = false
        }, 5000)
      }
    },
    // 加载结束...
    loading_end(keys) {
      if (Array.isArray(keys)) {
        keys.forEach((key) => {
          this.$nextTick(() => {
            this.loading[key] = false
          })
        })
      } else {
        this.$nextTick(() => {
          this.loading[keys] = false
        })
      }
    }
  }
}
</script>

<style lang="scss"></style>
